package com.myphoto.business.photo.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.myphoto.base.annotation.ProductSwagger;
import com.myphoto.base.annotation.SysLog;
import com.myphoto.base.config.properties.IConfig;
import com.myphoto.base.enumtype.LogTypeEnum;
import com.myphoto.base.enumtype.ModuleEnum;
import com.myphoto.base.enumtype.MsgEnum;
import com.myphoto.base.mybatis.photo.entity.VideoEntity;
import com.myphoto.base.util.R;
import com.myphoto.business.photo.service.VideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;

@RestController
@RequestMapping(value = "/video")
@Api(tags = "视频管理")
public class VideoController {

    @Autowired
    private VideoService videoService;
    @Autowired
    private IConfig config;

    /**
    * @description 查询视频列表
    * @author 方安伦
    * @date 2022/09/09 09:13
     **/
    @ApiOperation(value = "查询视频列表", notes = "查询视频列表",httpMethod="POST")
    @ApiOperationSupport( author = "方安伦")
    @RequestMapping("/loadVideoList")
    @ProductSwagger
    @SysLog(model = ModuleEnum.VIDEO,logType = LogTypeEnum.INFO,value = "查询视频列表",saveToDatabase = true)
    public R<List<VideoEntity>> loadVideoList() throws Exception{
        List<VideoEntity> videoList = videoService.loadVideoList();
        return R.success(MsgEnum.OPRATE_SUCCESS,videoList);
    }

    /**
     * @description 上传视频
     * @author 方安伦
     * @date 2022/09/09 09:22
     **/
    @ApiOperation(value = "上传视频", notes = "上传视频",httpMethod="POST")
    @ApiOperationSupport( author = "方安伦")
    @RequestMapping("/uploadVideo")
    @ApiImplicitParams({
            @ApiImplicitParam(name="lastModified",value="视频拍照时间（yyyy-MM-dd HH:mm:ss）",dataType="string", dataTypeClass= String.class,paramType = "query",required=true),
            @ApiImplicitParam(name="file",value="视频文件",dataType="__file", dataTypeClass = MultipartFile.class ,paramType = "query",required=true)
    })
    @SysLog(model = ModuleEnum.VIDEO,logType = LogTypeEnum.INFO,value = "上传视频")
    public R uploadVideo(String lastModified,@RequestPart(name="file") MultipartFile file) throws Exception{
        //1、检查视频文件是否已经存在
        String filename = file.getOriginalFilename();
        boolean flag = videoService.checkFileIsExist(filename);
        if(flag){
            return R.error("该视频文件已经存在！");
        }
        //2.检查视频信息是否已经存在
        boolean infoflag = videoService.checkFileInfoIsExist(filename);
        if(infoflag){
            return R.error("该视频信息已经存在！");
        }
        //3、上传视频
        videoService.uploadVideo(lastModified,file);
        return R.success(MsgEnum.UPLOAD_SUCCESS);
    }

    /**
    * @description 下载视频
    * @author 方安伦
    * @date 2022/9/9 09:26
    * @param fileName
     **/
    @ApiOperation(value = "下载视频", notes = "下载视频",httpMethod="POST")
    @ApiOperationSupport( author = "方安伦")
    @GetMapping(value="/downloadVideo/{fileName}")
    @SysLog(model = ModuleEnum.VIDEO,logType = LogTypeEnum.INFO,value = "下载视频")
    public void downloadVideo(HttpServletResponse response, @PathVariable(value = "fileName",required = true) String fileName) throws Exception{
        boolean flag = videoService.checkFileIsExist(fileName);
        if(flag==false){
            return ;
        }
        //拼接文件存储路径
        String video_path = config.getConfig().getVideo_path();//得到上传文件主路径
        String filePath = video_path + fileName;//得到文件的存储路径
        // 清空response
        response.reset();
        // 设置response的Header
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
        long fileLength = new File(filePath).length();
        response.setHeader("Content-Length", String.valueOf(fileLength));
        response.setContentType("application/octet-stream;charset=UTF-8");
        //获取 response 的输出流，用来输出文件
        ServletOutputStream out = response.getOutputStream();
        //读取，以输入流的形式读取文件
        FileInputStream in = new FileInputStream(filePath);
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = in.read(buffer))!=-1) {
            out.write(buffer, 0, len);
        }
        out.flush();
    }

    /**
    * @description 清除冗余视频信息
    * @author 方安伦
    * @date 2022/9/9 9:27
     **/
    @ApiOperation(value = "清除冗余视频信息", notes = "清除冗余视频信息",httpMethod="POST")
    @ApiOperationSupport( author = "方安伦")
    @RequestMapping("/clearErrorVideoinfo")
    @ProductSwagger
    @SysLog(model = ModuleEnum.VIDEO,logType = LogTypeEnum.INFO,value = "清除冗余视频信息",saveToDatabase = true)
    public R clearErrorVideoinfo() throws Exception{
        videoService.clearErrorVideoinfo();
        return R.success(MsgEnum.OPRATE_SUCCESS);
    }
}
